import { tencentAK } from '../../common/const.js'
import { myGetRequest, myPostRequest } from "../../utils/myRequest.js"
import { gcj02towgs84 } from '../../utils/coordtransform.js'
var consoleUtil = require('../../utils/consoleUtil.js');
var dateUtil = require('../../utils/dateUtil.js');
var mapService = require('../../service/mapService.js');
//var coordtransform =require('../../utils/coordtransform.js');
var QQMapWX = require('../../lib/qqmap-wx-jssdk.js');
let scenicList = require('../../data/data');
//index.js
//获取应用实例
const app = getApp();
const defaultScale = 14;

//定义全局变量
var totalMarker = [];
var curId = 1;
let includePointsData = [];
//移动点
var point = [];
var starRun = 0;
var countTooGetLocation = 0;
var total_micro_second = 0;
var meters = 0;
//ui相关
var bottomHeight = 0;
var windowHeight = 0;
var windowWidth = 0;
//Map组件
var mapId = 'mySignMap';
var qqmapsdk;
Page({
  data: {
    userInfo: {},
    //是否已经完成过当前路线
    isDone: false,
    //当前路线
    routeId: 0,
    //运动状态
    meters: 0,
    time: "0:00:00",
    sign: true,
    speed: 0,
    //地图默认中心点坐标
    longitude: '120.414721',
    latitude: '36.072530',
    //用户当前位置
    userCurlongitude: '',
    userCurlatitude: '',
    //地图缩放级别
    scale: defaultScale,
    markers: [],
    showUpload: true,
    //运动路线
    polyline: [2],
    //发生给服务器的位置数据
    traceList: [],
    //地图高度
    mapHeight: 0,
    selectAddress: '',
    centerLongitude: '',
    centerLatitude: '',
    currentMarkerId: 0,
    temtime:0,
  },

  onLoad: function (options) {
    var that = this;
    that.data.temtime=0;
    console.log("页面初始化");
    var userInfo;
    try {
       userInfo = wx.getStorageSync('userInfo');
      if (!userInfo) {
        wx.redirectTo({
          url: '../login/login'
        })
      }
    } catch (e) {
      // Do something when catch error
      console.log("页面初始化失败： "+e)
    }
    that.setData({
      userInfo : userInfo
    })
    //检测更新
    mapService.checkUpdate();
    // 接收参数
    let curMarker = JSON.parse(options.curMarker);
    let isDone = JSON.parse(options.isDone);
    that.setData({
      isDone:isDone
    })
    that.initMarkers(curMarker);
    var mapCtx1 = wx.createMapContext(mapId);
    // 显示所有标记点
    mapCtx1.includePoints({
      padding: [100],
      points: includePointsData //放入所有坐标轴的数组   并引用此方法
    });
  },

  onShow: function () {
    consoleUtil.log('onShow--------------------->');
    var that = this;
    //定位权限校验
    mapService.getBackgroundLocationRight(that);

    that.changeMapHeight();
    that.getCenterLocation();
    //渲染路线
    if(!that.data.isDone) {
      that.drawRouteTrace(that.data.routeId);
      }
    //请求地理位置信息,移动中心点坐标
    //mapService.requestLocation(that);

    //以及跑完这条路线才轨迹回显
    if(that.data.isDone){
      that.trackPlayback(that.data.userInfo.id, that.data.routeId)
    }
    
  },

  /**
   * 页面不可见时
   */
  onHide: function () {

  },
  //back出页面后 执行这个方法
  onUnload: function () {
    consoleUtil.log('onunload--------------------->');
    //关闭后台定位
    wx.stopLocationUpdate();

  },
  //页面初始化时设置地图高度
  changeMapHeight: function () {
    var that = this;
    var count = 0;
    wx.getSystemInfo({
      success: function (res) {
        consoleUtil.log('页面初始化时设置地图高度' + res);
        windowHeight = res.windowHeight;
        windowWidth = res.windowWidth;

        that.setMapHeight();
      },
    })
  },

  setMapHeight: function (params) {
    var that = this;
    that.setData({
      mapHeight: (windowHeight - bottomHeight) + 'px'
    })

  },
  //--------------------UI设置end---------------------

  /** 
   * 初始化地图
   */
  initMap: function () {
    var that = this;
    qqmapsdk = new QQMapWX({
      key: tencentAK
    });
    //that.getCenterLocation();
  },
  trackPlayback: async function (userId, routeId) {
    var mapCtx = wx.createMapContext(mapId);
    const res = await myGetRequest({ url: "/mytrace/getMytrace/?routeId=" + routeId + "&userId=" +userId });
    if (res.statusCode == 200) {
      if (res.data.code == 0) {
        const path = res.data.data;
        mapCtx.moveAlong({
          markerId: 0,
          path: path,
          duration: 8500,
        });
      }
      else {
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2500

        })
      }
    } else {
      wx.showToast({
        title: '网络错误！',
        icon: 'error',
        duration: 1500
      })
      return;
    }
  },
  /**
   * 
   * @param {路线id} routeId 
   */
  drawRouteTrace: async function (routeId) {
    var that = this;
    const res = await myGetRequest({ url: "/routeTrace/getTracebyRouteId?routeId=" + routeId });
    if (res.statusCode == 200) {
      if (res.data.code == 0) {
        const routeTrace = res.data.data;
        console.log("获取路线");
        console.log(routeTrace)
        that.setData({
          'polyline[0]': {
            points: routeTrace,
            color: '#1cbbb4',
            width: 8
          }
        })
      } else {
        console.log(res.data.message);
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2500

        })
      }
    } else {
      wx.showToast({
        title: '网络错误！',
        icon: 'error',
        duration: 1500
      })
      return;
    }
  },
  /**
   * 更新上传坐标点
   */
  updateCenterLocation: function (latitude, longitude) {
    var that = this;
    that.setData({
      centerLatitude: latitude,
      centerLongitude: longitude
    })
  },

  /**
   * 回到定位点
   */
  selfLocationClick: function () {
    var that = this;
    //还原默认缩放级别
    that.setData({
      scale: defaultScale
    })
    //必须请求定位，改变中心点坐标
    mapService.requestLocation(that);
  },

  /**
   * 移动到中心点
   */
  moveTolocation: function () {
    var mapCtx = wx.createMapContext(mapId);
    mapCtx.moveToLocation();
  },


  /**
   * 点击控件时触发
   */
  controlTap: function () {

  },

  /**
   * 点击地图时触发
   */
  bindMapTap: function () {
    //恢复到原始页
    this.adjustViewStatus(true);
  },

  adjustViewStatus: function (uploadStatus) {
    var that = this;
    that.setData({
      //显示marker
      //showDialog: uploadStatus,
    })
    that.changeMapHeight();
  },

  onShareAppMessage: function (res) {

  },

  /**
   * 拖动地图时回调
   * 视野发生变化时触发
   */
  regionChange: function (res) {
    var that = this;
    // 改变中心点位置  
    if (res.type == "end") {
      that.getCenterLocation();
    }
  },

  /**
   * 得到地图中心点坐标
   */
  getCenterLocation: function () {
    var that = this;
    var mapCtx = wx.createMapContext(mapId);
    mapCtx.getCenterLocation({
      success: function (res) {
        that.updateCenterLocation(res.latitude, res.longitude);
        //逆地址解析
        //mapService.regeocodingAddress(that,qqmapsdk);
        //that.queryMarkerInfo();
      }
    })
  },
  /**
   * 得到用户当前坐标
   */

  getUserCurLocation: async function () {
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.setData({
          userCurLocation: res.latitude,
          userCurlongitude: res.longitude,
        })
      },
    })
  },
  //-----------------------Marker相关处理逻辑------------------------

  initMarkers: function (curMarker) {
    var that = this;
    totalMarker = [];
    includePointsData = [];
    includePointsData.push(
      {
        latitude: curMarker.latitude,
        longitude: curMarker.longitude
      }
    )
    let begMarker = that.createBegMarker(curMarker);
    totalMarker.push(begMarker)
    totalMarker.push(curMarker)

    that.setData({
      markers: totalMarker,
      routeId: curMarker.routeId
    })
  }
  /**
   * 
   * 点击marker
   */
  ,
  bindMakertap: function (e) {
    var that = this;
    console.log('点击了marker');
    console.log(e);
    //导航,仅在起点触发
    if (e.markerId != 0) return;
    that.navigateStart()

  },
  toggleDialog: function () {
    this.setData({
      showDialog: false,
    })
  },
  /**
   * 创建marker
   */
  createBegMarker: function (curMarker) {
    includePointsData.push(
      {
        latitude: curMarker.beginLat,
        longitude: curMarker.beginLong
      }
    )
    let marker = {
      iconPath: '/assets/scenic/beg.png',
      id: 0,
      name: "起点",
      latitude: curMarker.beginLat,
      longitude: curMarker.beginLong,
      width: 30,
      height: 30,
      label: {
        content: "起点",
        color: '#0081ff',
        fontSize: 8,
        bgColor: "#fff",
        borderRadius: 30,
        borderColor: "#0081ff",
        borderWidth: 1,
        padding: 3,
        textAlign: "center"
      },
      callout: {
        content: "起点",
        fontSize: 0,
      }
    };
    return marker;
  },
  //------------------实时轨迹逻辑----------------------------------------------------------------------------
  //开始运动处理逻辑
  runstatus: async function () {
    var that = this;
    //回调函数记录坐标点信息-----------------------------------------
    //获取当前坐标，并计算两个坐标点距离
    const _locationChangeFn = function (res) {
      var lat, lng;
      //当前坐标值
      lat = res.latitude;
      lng = res.longitude;

      var pointArr = point;
      var len = pointArr.length;
      var lastPoint;
      if (len == 0) {
        point.push({ latitude: lat, longitude: lng });
        //记录要发往数据库的经纬度信息
        mapService.addTraceList(that, lat, lng, dateUtil.date_ymdhms(), that.data.userInfo.id, that.data.routeId);
      }
      len = pointArr.length;
      lastPoint = pointArr[len - 1];

      //使用腾讯地图api计算距离，返回 m 
      var newMeters = mapService.getDistance(lastPoint.latitude, lastPoint.longitude, res.latitude, res.longitude);


      //规定最小移动距离
      if (newMeters < 0.0015) {
        newMeters = 0.0;
      }
      meters = new Number(meters + newMeters);
      //规定最小速度
      var speed = res.speed;
      if (speed < 0.001) {
        speed = 0.0;
      }
      speed = speed.toFixed(2);

      point.push({ latitude: lat, longitude: lng });
      mapService.addTraceList(that, lat, lng, dateUtil.date_ymdhms(), that.data.userInfo.id, that.data.routeId);

      //绘制轨迹信息
      that.drawline();
      that.setData({
        latitude: res.latitude,
        longitude: res.longitude,
        meters: meters.toFixed(2),
        speed: speed
      });
      //todo
      //应该在这里判断是否偏移轨迹
      that.ifleave(res.latitude,res.longitude)
      //是否到达终点
      that.ifEnd(res.latitude,res.longitude) 
      //获取这条路线的数据信息，参考在java后端 getTraceByRouteId（）方法 ，具体的问我
    }
    //回调函数-----------------------------------------------------------------------
    starRun = 1;
    //开启计时器
    that.keepPaint(that);
    mapService.getBackgroundLocationRight(that);
    wx.onLocationChange(_locationChangeFn)


  },
  //计时器
  keepPaint: function () {
    var that = this;
    //递归结束条件
    if (starRun == 0) {
      return;
    }

    if (countTooGetLocation >= 100) {
      var time = dateUtil.date_format(total_micro_second);
      that.updateTime(time);
    }
    //这里控制多少秒获取一次位置信息
    //暂时弃用
    if (countTooGetLocation >= 2000) { //1000为1s
      countTooGetLocation = 0;
    }
    //递归逻辑
    setTimeout(function () {
      countTooGetLocation += 10;
      total_micro_second += 10;
      that.keepPaint(that);
    }, 10)
  },
  //更新时间
  updateTime: function (time) {
    this.setData({
      time: time,
    })

  },
  drawline: function () {
    this.setData({
      'polyline[1]': {
        points: point,
        color: '#0081ff',
        width: 4,
        dottedLine: false
      }
    });
  }
  ,
  /**
   * 采集路线时使用
   */
  sendTrace: function () {
    var that = this;
    var routeId = that.data.routeId;
    //起点坐标
    var begMarker = totalMarker[0];
    //这里是将string转为number类型，如果需要string类型，去掉Number即可
    var beglatitude = Number(begMarker.latitude);
    var beglongitude = Number(begMarker.longitude);
    //终点坐标
    var endMarker = totalMarker[1];
    var endlatitude = Number(endMarker.latitude);
    var endlongitude = Number(endMarker.longitude);

    var res = qqmapsdk.direction({
      mode: 'walking',
      from: {
        latitude: beglatitude,
        longitude: beglongitude
      },
      to: {
        latitude: endlatitude,
        longitude: endlongitude
      },
      success: function (res) {
        console.log("调用地图返回的路线值");
        console.log(res);
        console.log(res);
        var ret = res;
        var coors = ret.result.routes[0].polyline, pl = [];
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        var kr = 1000000;
        for (var i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
        }
        //将解压后的坐标放入点串数组pl中
        for (var i = 0; i < coors.length; i += 2) {
          pl.push({latitude: coors[i], longitude: coors[i + 1], routeId: routeId })
        }
        myPostRequest({
          url: '/routeTrace/addTrace',
          data: pl,
        })
        console.log(pl)
        //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
        that.setData({
          polyline: [{
            points: pl,
            color: '#FF0000DD',
            width: 4
          }]
        })
      }, fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
      }
    });



  },
  /**
   * 发送用户当前运动的轨迹
   */
  sendMyTrace: function () {
      const res = myPostRequest({
      url: '/mytrace/addTrace',
      data: that.data.traceList,
    })
    if (res.statusCode == 200 && res.data.code == 0) {
      that.setData({
        traceList: []
      })
      
      wx.showToast({
        title: '轨迹记录成功！',
        icon: 'none',
        duration: 2500
      })
    } else {
      wx.showToast({
        title: '网络错误',
        icon: 'error',
        duration: 2500

      })
    }
  },
  //----------------------------------------------------起点打卡处理逻辑----------------
  signStart: async function () {
    var that = this;
    //获取用户当前坐标
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        //业务逻辑-----------------------------
        //用户当前位置
        var userCurlatitude = res.latitude;
        var userCurlongitude = res.longitude;
        // 路线id
        var routeId = that.data.routeId;
        //起点坐标
        var begMarker = totalMarker[0];
        //这里是将string转为number类型，如果需要string类型，去掉Number即可
        var beglatitude = Number(begMarker.latitude);
        var beglongitude = Number(begMarker.longitude);

        //gcj02 to wgs84转化误差太大弃用ing
        // var res= gcj02towgs84(beglongitude,beglatitude);
        // console.log('转化坐标前坐标')
        // console.log('lat: '+beglatitude,'long: '+beglongitude);
        // console.log('转化坐标后坐标')
        // console.log(res);
        //终点坐标
        var endMarker = totalMarker[1];
        var endlatitude = Number(endMarker.latitude);
        var endlongitude = Number(endMarker.longitude);
        //用户id
        var userId = that.data.userInfo.id;
         wx.request({
            url: 'https://jianbuxing.qdszgh.cn/complete/signstart', // 服务器后端的地址
            data: {
              "longitude": userCurlongitude,
              "latitude": userCurlatitude,
              "routeid": routeId,
              "userid": userId,
              "beginLongitude":beglongitude,
              "beginLatitude":beglatitude
              // 传给后端的数据
            }, 
            header: {
              'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
            },

            method: "POST", // 请求的方式有Get和Post两种
            success(res) {
              if (res.data.code === 0) {
                // 切换按钮
                that.setData({
                  sign:false
                })
                // 开始健步行
                that.runstatus();

                wx.showToast({
                  title: '签到成功',
                  icon: 'success',
                })
                //这里写签到成功的逻辑代码

              } else {
                wx.showToast({
                  title: '未到起点位置',
                  icon: 'error',
                })
                //引导用户进行导航到达
                that.navigateStart();
                //这里写未到起点的逻辑代码
                return;
              }
            },
            fail(res){
              wx.showToast({
                title: '网络错误',
                icon: 'error',
              })
            }
          })

      },
    })
    //-----------------
  },
  /**
   * 立即停止打卡行为
   */
  stoprun: function () {
    //
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定要终点打卡/暂停打卡吗？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          //------------这里写其他业务逻辑
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              //业务逻辑-----------------------------
              //用户当前位置
              var userCurlatitude = res.latitude;
              var userCurlongitude = res.longitude;
              // 路线id
              var routeId = that.data.routeId;
              //起点坐标
              var begMarker = totalMarker[0];
              //这里是将string转为number类型，如果需要string类型，去掉Number即可
              var beglatitude = Number(begMarker.latitude);
              var beglongitude = Number(begMarker.longitude);

              var endMarker = totalMarker[1];
              var endlatitude = Number(endMarker.latitude);
              var endlongitude = Number(endMarker.longitude);
              //用户id
              var userId = that.data.userInfo.id;
      
               wx.request({
                  url: 'https://jianbuxing.qdszgh.cn/complete/refresh', // 服务器后端的地址
                  data: {
                    "userid": userId,
                    // 传给后端的数据
                  },
                  header: {
                    'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
                  },
      
                  method: "POST", // 请求的方式有Get和Post两种
                  success(res) {
                    //停止打卡状态
                    that.endRunstatus();
                    //返回到地图页面
                    // wx.switchTab({
                    //   url: '/pages/index/index'
                    // })
                  },
                })
      
            },
          })

        } else if (res.cancel) {
          return;
        }
      }
    })
  },
  /**
   * 停止运动
   */
  endRunstatus: function () {
    starRun = 0;
    //暂停计时器
    var that = this;
    that.keepPaint(that);
    console.log('关闭持续定位ingg');
    wx.stopLocationUpdate();
    // 计时器重置
    total_micro_second=0;
    //更换按钮
    that.setData({
      sign: true,
      point: []
    })
    // 删除运动路线
    that.drawline();
  },
  /**
   * 跳转到拍照打卡处理逻辑
   */
   navigatePhotoSign:function () {
    var that = this;
     //隐藏打卡相关按钮
    wx.navigateTo({
      url: "/pages/photosign/photosign?routeId=" + JSON.stringify(that.data.routeId)
    })
  },
  //导航至起点
  navigateStart: function () {
    var curMarker = totalMarker[0];
    var latitude = Number(curMarker.latitude);
    var longitude = Number(curMarker.longitude);
    wx.showModal({
      title: '提示',
      content: '是否导航至起点位置',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          //调用外部导航app导航至起点
          wx.openLocation({
            latitude,
            longitude,
            scale: 14,
            name: curMarker.name,
            address: '健步行起点'
          })
        } else if (res.cancel) {
          return;
        }
      }
    })
  },

  ifEnd: function (latitude , longitude) {
        //业务逻辑-----------------------------
        //用户当前位置
        var that = this;
        var userCurlatitude = latitude;
        var userCurlongitude = longitude;
        var routeId = that.data.routeId;

        //用户id
        var userId = that.data.userInfo.id;


        //终点坐标
        var endMarker = totalMarker[1];
        var endlatitude = Number(endMarker.latitude);
        var endlongitude = Number(endMarker.longitude);

         wx.request({
            url: 'https://jianbuxing.qdszgh.cn/complete/ifEnd', // 服务器后端的地址
            data: {
              "longitude": userCurlongitude,
              "latitude": userCurlatitude,
              "routeid": routeId,
              "userid": userId,
              "endLatitude":endlatitude,
              "endLongitude":endlongitude
              // 传给后端的数据
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
            },

            method: "POST", // 请求的方式有Get和Post两种
            success(res) {
              console.log(res.data.code)
              if (res.data.code === 0) {
                wx.showToast({
                  title: '到达终点',
                  icon: 'success',
                })
                      //例如到达终点需要执行 set idDone:true(显示拍照打卡按钮) , call that.endRunstatus();（结束运动）
                      that.setData({
                        idDone:true
                      })
                      // 记录轨迹信息
                      that.sendMyTrace();
                      // 停止运动状态
                      that.endRunstatus();
                      // 切换到打卡页面
                      that.navigatePhotoSign();
              }
            },
          })

      },
  ifleave: function (latitude , longitude) {
        //业务逻辑-----------------------------
        //用户当前位置
       var that = this;
        var userCurlatitude = latitude;
        var userCurlongitude = longitude;
        var routeId = that.data.routeId;

        //用户id
        var userId = that.data.userInfo.id;

         wx.request({
            url: 'https://jianbuxing.qdszgh.cn/complete/ifleave', // 服务器后端的地址
            data: {
              "longitude": userCurlongitude,
              "latitude": userCurlatitude,
              "routeid": routeId,
              "userid": userId,
              // 传给后端的数据
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
            },

            method: "POST", // 请求的方式有Get和Post两种
            success(res) {
              console.log(res.data.code)
              if (res.data.code === 0) {//偏离路线，此处写偏离路线的逻辑
                console.log(that.data.temtime+"$$$$$$$$$$$$$$$$$$$$$$")
                if(that.data.temtime==0){
                  console.log("路线偏移首次出现！！！！！！！！！！！！！！！！！！！")
                  that.data.temtime=res.data.data;
                  wx.showToast({
                    title: '路线偏离',
                    icon: 'error',
                    duration:10000,
                  })
                }
                else{
                    if(res.data.data-that.data.temtime>120000){
                        console.log("路线偏移超过了2分钟！！！！！！！！！！！！！！！！！结束健步行！！！！")
                        that.data.temtime=0;
                        that.endRunstatus();                    
                    }
                    else{
                    console.log("路线偏移弹窗")
                      wx.showToast({
                        title: '路线偏离',
                        icon: 'error',
                      })
                    }
                }
                wx.showToast({
                  title: '路线偏离',
                  icon: 'error',
                })

              }
              else{

              }
            },
          })

      },

  
  

})

//1.偏离路线逻辑处理879